package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.GoodsValueAddedServicesDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.*;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.dao.ValueAddedServicesDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("valueAddedServicesService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class ValueAddedServicesService extends BaseServiceImpl<ValueAddedServices> {

	@Resource
	private ValueAddedServicesDao valueAddedServicesDao;
	@Resource
	private UserDao userDao;
	@Resource
	private Memcached memcached;
	@Resource
	private GoodsValueAddedServicesDao goodsValueAddedServicesDao;


	@Override
	protected BaseDao <ValueAddedServices> getDao() {
		return valueAddedServicesDao;
	}
	/*
	*zlq
	* 添加增值服务
	* token:
	* name:名称
	*price：价格
	* detailsUrl：详情地址
	* warrantyPeriod:服务期限
	* valueAddedServicesType：服务类型 1:按次服务 2:按月服务
	* next：服务次数
	* label:标签
	* valueAddedServicesKind:服务种类1:碎屏服务 2:延保服务3：进水服务
	* state:状态
	 */
	public  String add(ModelMap model, String token,String name,String price,String detailsUrl,String warrantyPeriod,String valueAddedServicesType,String next,String label,String valueAddedServicesKind,boolean state){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(StringUtils.isEmpty(name)){
			return CodeContent.getModelByCode(0, "服务名称不能为空", model);
		}
		if(StringUtils.isEmpty(price)){
			return CodeContent.getModelByCode(0, "服务价格不能为空", model);
		}
		if(StringUtils.isEmpty(detailsUrl)){
			return CodeContent.getModelByCode(0, "服务详情路径", model);
		}
		if(!NumberUtils.isDigits(warrantyPeriod)){
			return CodeContent.getModelByCode(0, "服务期限不能为空", model);
		}
		if(!NumberUtils.isDigits(valueAddedServicesType)){
			return CodeContent.getModelByCode(0, "服务类型不能为空", model);
		}
		if(ValueAddedServicesType.getByIntValue(Integer.parseInt(valueAddedServicesType))==null){
			return CodeContent.getModelByCode(0, "服务类型不正确", model);
		}
		if(!NumberUtils.isDigits(valueAddedServicesKind)){
			return CodeContent.getModelByCode(0, "服务种类不能为空", model);
		}
		if(ValueAddedServicesKind.getByIntValue(Integer.parseInt(valueAddedServicesType))==null){
			return CodeContent.getModelByCode(0, "服务种类不正确", model);
		}
		if(ValueAddedServicesType.getByIntValue(Integer.parseInt(valueAddedServicesType)).equals(ValueAddedServicesType.ByNext)){
			if(!NumberUtils.isDigits(next)){
				return CodeContent.getModelByCode(0, "按次服务时，次数不能为空", model);
			}
		}
		if(StringUtils.isEmpty(label)){
			return CodeContent.getModelByCode(0, "标签不能为空", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"ADDValueAddedServices");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"ADDValueAddedServices",5,"1");
		}
		ValueAddedServices valueAddedServices=valueAddedServicesDao.getByLabel(label.trim());
		if(valueAddedServices!=null){
			return CodeContent.getModelByCode(0, "标签名已存在", model);
		}else {
			valueAddedServices=new ValueAddedServices();
		}

		valueAddedServices.setName(name.trim());
		valueAddedServices.setDetailsUrl(detailsUrl.trim());
		valueAddedServices.setPrice(new BigDecimal(price));
		valueAddedServices.setWarrantyPeriod(Integer.parseInt(warrantyPeriod));
		valueAddedServices.setValueAddedServicesTypeValue(Integer.parseInt(valueAddedServicesType));
		valueAddedServices.setValueAddedServicesKindValue(Integer.parseInt(valueAddedServicesKind));
		valueAddedServices.setLabel(label.trim());
		valueAddedServices.setState(state);
		if(valueAddedServices.getValueAddedServicesType().equals(ValueAddedServicesType.ByNext)){
			valueAddedServices.setNext(Integer.parseInt(next));
		}
		valueAddedServicesDao.add(valueAddedServices);

		return CodeContent.getModelByCode(1, "", model);
	}
	/*
	*查询所有的增值服务名称
	* zlq
	 */
	public String getValueAddedServices(ModelMap model,String valueAddedServicesKindValue) {
		ValueAddedServices valueAddedServices = new ValueAddedServices();
		valueAddedServices.setState(true);
		valueAddedServices.setValueAddedServicesKindValue(Integer.parseInt(valueAddedServicesKindValue));
		if(valueAddedServices.getValueAddedServicesKind()==null){
			CodeContent.getModelByCode(0, "服务种类不正确", model);
		}
		List<ValueAddedServices> valueAddedServicesList = valueAddedServicesDao.queryPageView(-1, -1, valueAddedServices).getRecords();
		return CodeContent.getModelByCode(1, "", convertList(valueAddedServicesList));
	}

		public List<ModelMap> convertList(List<ValueAddedServices> valueAddedServicesList){
			List<ModelMap> list = new ArrayList<ModelMap>();
			if (valueAddedServicesList != null && valueAddedServicesList.size() > 0) {
				for (ValueAddedServices valueAddedServices : valueAddedServicesList) {
					ModelMap map = buildModelList(valueAddedServices);
					list.add(map);
				}
			}
			return list;
		}
		public ModelMap buildModelList(ValueAddedServices valueAddedServices) {
			ModelMap model = new ModelMap();
			model.put("id",valueAddedServices.getId());
			model.put("name",valueAddedServices.getName());
			model.put("price",valueAddedServices.getPrice());
			model.put("detailsUrl",valueAddedServices.getDetailsUrl());
			return  model;
		}
	/*
	*CRM查询增值服务列表
	* zlq
	* token:
	* page:页码
	 */
	public String getList(ModelMap model, String token,String page,String valueAddedServicesKind){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		ValueAddedServices valueAddedServices=new ValueAddedServices();
		if(NumberUtils.isDigits(valueAddedServicesKind)){
			valueAddedServices.setValueAddedServicesKindValue(Integer.parseInt(valueAddedServicesKind));
		}
		pageview=valueAddedServicesDao.queryPageView(pageNo, pageSize,valueAddedServices);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return new JSONObject(model).toString();

	}
	public List<ModelMap> convertCrmList(List<ValueAddedServices> valueAddedServicesList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (valueAddedServicesList != null && valueAddedServicesList.size() > 0) {
			for (ValueAddedServices valueAddedServices : valueAddedServicesList) {
				ModelMap map = buildModelCrmList(valueAddedServices);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmList(ValueAddedServices valueAddedServices) {
		ModelMap model = new ModelMap();
		model.put("id",valueAddedServices.getId());
		model.put("name",valueAddedServices.getName());
		model.put("price",valueAddedServices.getPrice());
		model.put("warrantyPeriod",valueAddedServices.getWarrantyPeriod());
		model.put("valueAddedServicesType",valueAddedServices.getValueAddedServicesType().toString());
		model.put("valueAddedServicesTypeValue",valueAddedServices.getValueAddedServicesTypeValue());
		model.put("valueAddedServicesKind",valueAddedServices.getValueAddedServicesKind().toString());
		model.put("valueAddedServicesKindValue",valueAddedServices.getValueAddedServicesKindValue());

		model.put("next",valueAddedServices.getNext()!=null?valueAddedServices.getNext():"");
		model.put("detailsUrl",valueAddedServices.getDetailsUrl()!=null?valueAddedServices.getDetailsUrl():"");
		model.put("label",valueAddedServices.getLabel());
		model.put("state",valueAddedServices.getState()?"有效":"无效");
		model.put("stateValue",valueAddedServices.getState()?"1":"0");
		return  model;
	}

			/*
	*查询商品增值服务列表
	* zlq
	 */
	public String getGoodsValueAddedServices(ModelMap model,String goodsId){
		List<ValueAddedServices> valueAddedServicesList =new ArrayList<ValueAddedServices>();
		if(NumberUtils.isDigits(goodsId)) {
			 valueAddedServicesList=valueAddedServicesDao.getByGoodsId(Integer.parseInt(goodsId));
		}
		return  CodeContent.getModelByCode(1, "", convertList(valueAddedServicesList));
	}

	/*
* 传入商品的增值服务和goodsid然后计算一共节省的金钱
* */
	public Map<String,Object> serviceMoney(String addServiceId){
		Map<String,Object> map = new HashMap<String, Object>();
		BigDecimal servieMoney = new BigDecimal(0);
		String[] args = addServiceId.split(",");
		for(int i=0;i<args.length;i++){
			ValueAddedServices valueAddedServices = valueAddedServicesDao.getById(Integer.valueOf(args[i]));
		    if(valueAddedServices==null||valueAddedServices.getState()==false){
				 map.put("code",0);
				 map.put("msg","serviceid:"+args[i]+"失效，或者不存在");
                 return map;
			}else{
                   servieMoney = servieMoney.add(valueAddedServices.getPrice());


			}

		}
		map.put("serviceNum",args.length);//ffl   购买增值服务个数
		map.put("serviceMoney",servieMoney);
		map.put("code",1);
		map.put("msg","success");
		return  map;

	}

	/*
	*zlq
	* 修改增值服务
	* token:
	* name:名称
	*price：价格
	* detailsUrl：详情地址
	* warrantyPeriod:服务期限
	* valueAddedServicesType：服务类型 1:按次服务 2:按月服务
	* next：服务次数
	* valueAddedServicesKind:服务种类1:碎屏服务 2:延保服务3：进水服务
	* state:状态
	 */
	public  String modification(ModelMap model, String token,String id,String name,String price,String detailsUrl,String warrantyPeriod,String valueAddedServicesType,String next,String valueAddedServicesKind,boolean state){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(StringUtils.isEmpty(id)){
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "ID不为数字", model);
		}
		if(StringUtils.isEmpty(name)){
			return CodeContent.getModelByCode(0, "服务名称不能为空", model);
		}
		if(StringUtils.isEmpty(price)){
			return CodeContent.getModelByCode(0, "服务价格不能为空", model);
		}
		if(StringUtils.isEmpty(detailsUrl)){
			return CodeContent.getModelByCode(0, "服务详情路径", model);
		}
		if(!NumberUtils.isDigits(warrantyPeriod)){
			return CodeContent.getModelByCode(0, "服务期限不能为空", model);
		}
		if(!NumberUtils.isDigits(valueAddedServicesType)){
			return CodeContent.getModelByCode(0, "服务类型不能为空", model);
		}
		if(ValueAddedServicesType.getByIntValue(Integer.parseInt(valueAddedServicesType))==null){
			return CodeContent.getModelByCode(0, "服务类型不正确", model);
		}
		if(!NumberUtils.isDigits(valueAddedServicesKind)){
			return CodeContent.getModelByCode(0, "服务种类不能为空", model);
		}
		if(ValueAddedServicesKind.getByIntValue(Integer.parseInt(valueAddedServicesType))==null){
			return CodeContent.getModelByCode(0, "服务种类不正确", model);
		}
		if(ValueAddedServicesType.getByIntValue(Integer.parseInt(valueAddedServicesType)).equals(ValueAddedServicesType.ByNext)){
			if(!NumberUtils.isDigits(next)){
				return CodeContent.getModelByCode(0, "按次服务时，次数不能为空", model);
			}
		}
		//防止重复提交
		Object o = memcached.get(id+"modificationValueAddedServices");
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", model);
		}else {
			memcached.set(id+"modificationValueAddedServices",5,"1");
		}
		ValueAddedServices valueAddedServices=valueAddedServicesDao.getById(Integer.parseInt(id));
		if(valueAddedServices==null){
			return CodeContent.getModelByCode(0, "增值服务ID不存在", model);
		}
		valueAddedServices.setName(name.trim());
		valueAddedServices.setDetailsUrl(detailsUrl.trim());
		valueAddedServices.setPrice(new BigDecimal(price));
		valueAddedServices.setWarrantyPeriod(Integer.parseInt(warrantyPeriod));
		valueAddedServices.setValueAddedServicesTypeValue(Integer.parseInt(valueAddedServicesType));
		valueAddedServices.setValueAddedServicesKindValue(Integer.parseInt(valueAddedServicesKind));
		valueAddedServices.setState(state);
		if(valueAddedServices.getValueAddedServicesType().equals(ValueAddedServicesType.ByNext)){
			valueAddedServices.setNext(Integer.parseInt(next));
		}
		valueAddedServicesDao.modify(valueAddedServices);
		//如果将状态改为有效，删除商品增值服务对应关系中的该条数据的对应关系
		if(!state){
			GoodsValueAddedServices goodsValueAddedServices=new GoodsValueAddedServices();
			goodsValueAddedServices.setValueAddedServicesId(valueAddedServices.getId());
			List<GoodsValueAddedServices> goodsValueAddedServicesList=goodsValueAddedServicesDao.queryList(-1,-1,goodsValueAddedServices);
			for(GoodsValueAddedServices goodsValueAddedServices2:goodsValueAddedServicesList){
				goodsValueAddedServicesDao.delete(goodsValueAddedServices2.getId());
			}
		}
		return CodeContent.getModelByCode(1, "", model);
	}

	public String getDetails(ModelMap model, String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(StringUtils.isEmpty(id)){
			return CodeContent.getModelByCode(0, "ID不能为空", model);
		}
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "ID不为数字", model);
		}
		ValueAddedServices valueAddedServices=valueAddedServicesDao.getById(Integer.parseInt(id));
		if(valueAddedServices==null){
			return CodeContent.getModelByCode(0, "增值服务ID不存在", model);
		}
		return CodeContent.getModelByCode(1, "", buildModelCrmList(valueAddedServices));
	}


}